<template>
  <div>
    <el-breadcrumb>
      <el-breadcrumb-item>首页</el-breadcrumb-item>
      <el-breadcrumb-item v-breadcrumb-certify></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="content compus">
      <el-row>
        <el-col :span="12">
          <e-heading style="margin-top:0;" :grade="'1'">校区列表</e-heading>
        </el-col>
        <el-col :span="12" style="text-align:right;">
          <router-link :to="{
            path: '/training/campus/add'
          }">
            <el-button size="small" type="primary"> 新增校区</el-button>
            </router-link>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-form v-bind="getFormProps()">
          <el-col :span="9">
            <el-form-item label="省市：">
              <el-select v-model="initValue" clearable placeholder="请选择" size="small">
                <el-option
                  v-for="item in selectionOption"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-input v-model="query.schoolName" placeholder="请输入校区名称" size="small"></el-input>
          </el-col>
          <el-col :span="6">
            <el-button type="primary-plain" class="search-btn" native-type="submit" size="small">搜索</el-button>
          </el-col>
        </el-form>
      </el-row>
      <div v-if="schoolList.list && schoolList.list.length">        
        <!--<el-button class="fr" type="primary">导出课程表(单个)</el-button>-->
        <el-table
          class="campus-table"
          :data="schoolList.list"
          tooltip-effect="dark"
          style="width: 100%">
          <el-table-column
            label="校区名称"
            show-overflow-tooltip>
            <template slot-scope="scope">{{ scope.row.schoolName }}</template>
          </el-table-column>
          <el-table-column
            prop="listTrainVenuesAddress"
            label="城市"
            align="center"
            show-overflow-tooltip
            width="160">
            <template slot-scope="scope">
              {{scope.row.cityName ? scope.row.cityName : '-'}}
            </template>
          </el-table-column>
          <el-table-column
            prop="address"
            label="详细地址"
            align="center"
            width="260"
            show-overflow-tooltip>
            <template slot-scope="scope">
              <span v-if="scope.row.latitude">{{scope.row.address}}</span>
              <span v-else>{{scope.row.provinceName + scope.row.cityName + scope.row.areaName + scope.row.address}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="managerPhone"
            label="电话"
            align="center"
            width="150"
            show-overflow-tooltip>
            <template slot-scope="scope">
              {{scope.row.managerPhone ? scope.row.managerPhone : '-'}}
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="70"
            class="center">
            <template slot-scope="scope" >
              <el-button @click="handleEdit(scope.row)" type="link">编辑</el-button>
              <el-button style="margin-left: 0;" @click="handleDelete(scope.row)" type="link">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-bind="getPaginationProps(schoolList)"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange">
        </el-pagination>
      </div>
  
      <e-placeholder v-else 
        :src="'/static/images/no-school.jpg'" 
        :text="'点击“新增校区”来设置校区吧，设置完成即可发布课程。'">
      </e-placeholder>
  

      <el-dialog 
        v-if="dVisible"
        :visible.sync="dVisible"
        :title="isEdit ? '编辑校区': '新增校区' " 
        class="compus_dialog"
        :before-close="hideDialog">          
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
          <el-scrollbar  wrap-class="form-wrapper">
          <el-form-item
            prop="schoolName"
            label="校   区："
            :rules="[
                { required: true, message: '请输入校区名称'},
                { validator: schoolNameExist, message: '校区名称已存在', trigger: 'blur'}
            ]">
            <el-input class="fl add-input" v-model.trim="form.schoolName" :maxlength="50"  placeholder="请输入校区名称" style="90%"></el-input>
          </el-form-item>

          <el-form-item label="负责人：">
            <el-input class="fl add-input" v-model.trim="form.manager" :maxlength="20" placeholder="请输入负责人名称"></el-input>
          </el-form-item>
          <el-form-item label="电 话：" 
            prop="managerPhone"
            :rules="[
              form.managerPhone ? validator.rule.isPhoneAndLandline : ''
            ]">
            <el-input class="fl add-input" v-model.trim="form.managerPhone" placeholder="请输入负责人电话"></el-input>
          </el-form-item>
          <el-form-item label="地图坐标：">
            <Map @mapUpdata="getMapData" :mapAddress="mapAddress" :longitude="form.longitude" :latitude="form.latitude"></Map>
          </el-form-item>

          <el-form-item 
            prop="address"
            label="详细地址："
            :rules="[{ required: true, message: '请选择省市区，输入详细地址'}]">
              <div style="text-align:left">
                <e-address-cascader style="margin-bottom: 15px;width: 85%;"
                  v-if="!mapAddress"
                  placeholder="请选择省市区"  
                  v-model="form.area" :grade="3" 
                  :label.sync="form.location">
                </e-address-cascader>
                <el-input class="fl add-input" v-model.trim="form.address" :maxlength="50" placeholder="请输入详细地址"></el-input>&nbsp;<el-button type="link" style="line-height:36px;" @click="handleResetAddress" v-if="mapAddress">修改地址</el-button>
              </div>
          </el-form-item>
          
          <el-form-item 
            prop="listTrainVenuesAddress"
            label="上课地点："
            :rules="[
                { required: true, message: '请输入上课地点'},
                Object.assign({}, validator.rule.venuesAddress,{message: '上课地点不能为空'})
            ]">
            <div v-for="(item,index) in form.listTrainVenuesAddress" :key="index" class="address-item" v-show="item.status == 1">
              <el-input  placeholder="请输入该校区的上课场地、场馆或教室名称" :maxlength="10" v-model.trim="item.address" :disabled="item.readonly" class="address-input" @blur="handleCheckRepetition(item.address)">
              </el-input>
              <template v-if="!item.readonly">
                <el-button icon="plus" class="btn-icon" v-if=" index == form.listTrainVenuesAddress.length -1 "
                  @click="handlePlusAddress()" :disabled="index == maxAddressLength - 1"></el-button>
                <el-button icon="minus" class="btn-icon" v-else
                  @click="handleMinusAddress(index)" ></el-button>
              </template>
              <template v-else >
                <el-button icon="plus" class="btn-icon" v-if=" index == form.listTrainVenuesAddress.length -1 || form.listTrainVenuesAddress.length<=1 "
                  @click="handlePlusAddress()" :disabled="index == maxAddressLength - 1"></el-button>
              </template>    
            </div>
          </el-form-item>
          
          <el-form-item 
            prop="transitInfo"
            label="交通信息：">
            <el-row class="mb20">
              <el-col :span="3">
                <el-button>地铁</el-button>
              </el-col>
              <el-col :span="18">
                <el-input v-model.trim="form.metroInfo"></el-input>
              </el-col>
            </el-row>
            <el-row class="mb20">
              <el-col :span="3">
                <el-button>公交</el-button>
              </el-col>
              <el-col :span="18">
                <el-input v-model.trim="form.transitInfo"></el-input>
              </el-col>
            </el-row>
            <el-row class="mb20">
              <el-col :span="3">
                <el-button>停车</el-button>
              </el-col>
              <el-col :span="18">
                <el-input v-model.trim="form.parkInfo"></el-input>
              </el-col>
            </el-row>     
            <p class="small center" style="width:300px;">完善校区信息，有助于买家更了解学校信息哦！</p>     
          </el-form-item>
          </el-scrollbar>
        </el-form>
        <span slot="footer" class="dialog-footer center">
          <el-button @click="hideDialog">取 消</el-button>
          <el-button type="primary" @click="handleSave">保 存</el-button>
        </span>
      </el-dialog>

    </div>
  </div>
</template>
<script>
import { pagingList } from 'utils/mixins'
import Api from 'api/train'
import validator from 'utils/validator'
import EGroup from '@e-ui/Group'
import EAddressCascader from '@e-ui/AddressCascader'
import { mapGetters } from 'vuex'
import Map from './components/Map'
import VueAMap from 'vue-amap' // 引入搞得地图组件
let amapManager = new VueAMap.AMapManager()
export default {
  mixins: [pagingList],
  components: {
    EAddressCascader,
    EGroup,
    Map
  },
  computed: {
    ...mapGetters({
      train_compus_selection: 'train_compus_selection' // 学员列表数据
    }),
    selectionOption () {
      let option = []
      for (let i = 0; i < this.train_compus_selection.length; i++) {
        option.push({
          label: this.train_compus_selection[i].provinceName + '-' + this.train_compus_selection[i].cityName,
          value: this.train_compus_selection[i].provinceId + '-' + this.train_compus_selection[i].cityId
        })
      }
      return option
    },
    initValue: {
      set (value) {
        value = value.split('-')
        this.query.provinceId = value[0] || null
        this.query.cityId = value[1] || null
      },
      get (value) {
        if (this.query.provinceId === null || this.query.cityId === null) {
          return ''
        }
        value = this.query.provinceId + '-' + this.query.cityId
        return value
      }
    }
  },
  mounted () {
    this.getProvinceAndCities()
  },
  data () {
    let schoolNameExist = (rule, value, callback) => {
      let self = this
      if (self.oldName !== self.form.schoolName) {
        Api.schoolNameValid({schoolName: value}).then((res) => {
          if (res.data === true) { // 校区名可用
            callback()
          }
          callback(new Error('校区名称已存在'))
        })
      } else {
        callback()
      }
    }
    return {
      amapManager,
      // 这里通过高德 SDK 完成。
      geocoder: new AMap.Geocoder({ // eslint-disable-line
        radius: 1000,
        extensions: 'all'
      }),
      schoolNameExist,
      validator,
      isEdit: false,
      query: this.getQuery({schoolName: this.$route.query.schoolName || null, provinceId: this.$route.query.provinceId || null, cityId: this.$route.query.cityId || null}),
      dVisible: false,
      selectedList: [],
      mapAddress: '',
      schoolList: {},
      school: {},
      rules: {},
      maxAddressLength: 10,
      form: {
        schoolName: '',
        manager: '',
        managerPhone: '',
        address: '', // 详细地址
        metroInfo: '',
        transitInfo: '',
        parkInfo: '',
        longitude: 0,
        latitude: 0,
        status: 1,
        orgUserId: '',
        createdTime: new Date().getTime(),
        id: '',
        listTrainVenuesAddress: [{
          id: '',
          schoolId: '',
          address: '',
          status: 1
        }], // 上课地点
        modifyId: '',
        area: [],
        location: '',
        provinceId: '',
        cityId: '',
        areaId: ''
      },
      OldName: '',
      selectionValue: ''
    }
  },
  methods: {
    fetch () {
      Api.schoolList(this.query).then((res) => {
        this.schoolList = res.data
        if (this.schoolList.list) {
          this.schoolList.list.forEach((item, index) => {
            this.getCityName(item, item.longitude, item.latitude)
          })
        }
      })
    },
    hideDialog (item) {
      // if (this.form.id && !this.form.schoolName) {
      this.fetch()
      // }
      this.dVisible = false
      this.mapAddress = ''
    },
    handleDelete (item) {
      Api.removeValid({schoolId: item.id}).then((res) => {
        if (res.data === true) {
          this.$confirm('删除后不可恢复，确认删除该校区吗？', '提示', {
            type: 'warning'
          }).then(() => {
            Api.deleteSchool({schoolId: item.id}).then((res) => {
              this.fetch()
              this.getProvinceAndCities()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            })
          })
        } else {
          this.$alert(res.msg, '提示', {
            confirmButtonText: '我知道了',
            callback: action => {
            }
          })
        }
      })
    },
    handleEdit (item) {
      this.$router.push({
        path: '/training/campus/edit',
        query: {
          id: item.id
        }
      })
      /*
      this.OldName = item.schoolName
      this.isEdit = true
      let readOnlyList = []
      let addressList = item.listTrainVenuesAddress
      Api.editValidate({schoolId: item.id}).then((res) => {
        readOnlyList = res.data
        this.dVisible = true
        this.oldName = item.schoolName
        this.form = item
        if (item.longitude) {
          this.mapAddress = item.address
        }
        this.form.area = []
        this.form.area.push(item.provinceId)
        this.form.area.push(item.cityId)
        this.form.area.push(item.areaId)
        for (let i = 0, len = readOnlyList.length; i < len; i++) {
          for (let j = 0, jlen = addressList.length; j < jlen; j++) {
            if (readOnlyList[i] === addressList[j].id) {
              addressList[j].readonly = true
            }
          }
        }
        if (!this.form.listTrainVenuesAddress.length) {
          this.form.listTrainVenuesAddress = []
          this.form.listTrainVenuesAddress.push({
            id: '',
            schoolId: item.id,
            address: '',
            status: 1
          })
        }
      })
      */
    },
    handleSave () {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          let f = this.form
          Api.addSchool({
            id: f.id,
            schoolName: f.schoolName,
            manager: f.manager,
            managerPhone: f.managerPhone,
            address: f.address,
            transitInfo: f.transitInfo,
            metroInfo: f.metroInfo,
            parkInfo: f.parkInfo,
            longitude: f.longitude,
            latitude: f.latitude,
            status: f.status,
            orgUserId: f.orgUserId,
            listTrainVenuesAddress: f.listTrainVenuesAddress,
            provinceId: f.area[0],
            cityId: f.area[1],
            areaId: f.area[2] || 0
          }, this).then((res) => {
            this.fetch()
            this.getProvinceAndCities()
            this.dVisible = false
            this.mapAddress = ''
          })
        } else {
          return false
        }
      })
    },
    handleAdd () {
      this.isEdit = false
      this.dVisible = true
      this.form = {
        id: '',
        schoolName: '',
        address: '',
        metroInfo: '',
        transitInfo: '',
        parkInfo: '',
        longitude: 0,
        latitude: 0,
        status: 1,
        orgUserId: '',
        createdTime: new Date().getTime(),
        listTrainVenuesAddress: [
          {
            id: '',
            schoolId: '',
            address: '',
            status: 1
          }
        ],
        area: [],
        location: '',
        provinceId: '',
        cityId: '',
        areaId: ''
      }
    },
    handleCheckRepetition (val) { // 校验上课地点不能重复
      let nullArray = []
      if (val && this.form.listTrainVenuesAddress && this.form.listTrainVenuesAddress.length > 0) {
        this.form.listTrainVenuesAddress.forEach((item, i) => {
          if (nullArray.includes(item.address)) {
            this.form.listTrainVenuesAddress[i].address = ''
            this.$message({
              message: '同一校区上课地点不能重复',
              type: 'error'
            })
          } else {
            nullArray.push(item.address)
          }
        })
      }
    },
    // 添加上课地点
    handlePlusAddress () {
      this.form.listTrainVenuesAddress.push({
        id: '',
        schoolId: this.form.id || '',
        address: '',
        status: 1
      })
    },
    // 删除上课地点
    handleMinusAddress (i) {
      this.form.listTrainVenuesAddress[i].status = 0
    },
    getProvinceAndCities () {
      this.$store.dispatch('train_compus_selection')
    },
    getMapData (mapData) { // 获取地图数据
      this.mapAddress = mapData.adress
      this.form.longitude = mapData.lng
      this.form.latitude = mapData.lat
      this.form.address = this.mapAddress
      this.form.area = [0, 0, 0]
    },
    handleResetAddress () { // 清除地图数据修改地址
      this.mapAddress = ''
      this.form.address = ''
      this.form.longitude = 0
      this.form.latitude = 0
    },
    getCityName (obj, lng, lat) {
      let scope = this
      if (lng && lat) {
        scope.geocoder.getAddress([lng, lat], function (status, result) {
          if (status === 'complete' && result.info === 'OK') {
            if (result && result.regeocode) {
              // 生成坐标地址
              obj.cityName = result.regeocode.addressComponent.city || result.regeocode.addressComponent.province
            }
          }
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.campus-table{
  margin: 20px 0;
}
.center{
  text-align: center;
}
.no-data{
  padding-top: 50px;
  p{
    color: #333;
    margin: 20px 0 30px;
  }
}
.mb20{
  margin-bottom: 20px;
  margin-right:15px;
  .el-button{
    min-width:0;
    padding-left: 10px;
    padding-right: 10px;
  }
}
.add-input{
  width:85%;
}
.address-item{
  margin-bottom: 10px;
  text-align: left;
}
.address-input{
  width: 76%;
}
</style>
<style lang="scss">
.form-wrapper{
  max-height: 560px;
  overflow-y: scroll;
}
.campus-table tr td {
  font-size: 12px;
}
.compus .el-form-item__content > .el-select{
  width:auto
}
.compus_dialog{
  .el-dialog--small{
    width:750px;
  }
}
</style>
